package com.zdb.java.tools.file;

import java.io.File;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MavenCleaner {

    private static ExecutorService pool = new ThreadPoolExecutor(10, 10, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));

    private static final String DIR_NAME = "node_modules";
    private static final String FILE_NAME = "package.json";

    public static void main(String[] args) {

        String dirPath = args[0];
        cleanDir(new File(dirPath), DIR_NAME, FILE_NAME);
    }

    /**
     *
     * @param dirFile 清理的目录文件
     * @param dirName 需要删除的目录名
     * @param fileName 同级目录下需要存在的文件名
     */
    private static void cleanDir(File dirFile, String dirName, String fileName) {
        if(!dirFile.exists()) {
            return;
        }
        File[] files = dirFile.listFiles();
        boolean hasPom = false;
        boolean hasTarget = false;
        File targetDir = null;
        for (File f : files) {
            if (f.isFile() && f.getName().equals(fileName)) {
                hasPom = true;
            } else if (f.isDirectory() && f.getName().equals(dirName)) {
                hasTarget = true;
                targetDir = f;
            } else if (f.isDirectory()) {
                cleanDir(f,DIR_NAME, FILE_NAME);
            }
        }
        if (hasPom && hasTarget) {
            delFile(targetDir, true);
        }
    }

    static boolean delFile(File file, boolean isRoot) {

        if(1==2) {
            System.out.println(file.getAbsolutePath());
            return false;
        }
        if(isRoot) {
            System.out.println("--- 删除文件 ---" + file.getAbsolutePath());
        }

        if (!file.exists()) {
            return false;
        }

        if (file.isFile()) {
            return file.delete();
        } else {
            File[] files = file.listFiles();
            for (File f : files) {
                delFile(f, false);
            }
            return file.delete();
        }
    }

}
